package com.example.ticket.demo.ticket;

import com.example.ticket.demo.model.table.Ticket;
import com.example.ticket.demo.service.ITicketService;
import com.example.ticket.demo.utils.SpringUtils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


/**
 * 售票
 * 
 * @author liu.nh
 *
 */
public class TicketSaleManager {

	private static ITicketService ticketService;
	
	private Lock lock = new ReentrantLock();
	
	static{
		ticketService = SpringUtils.getBean("ticketService");
	}
	
	public void sale3(String salerName) {
		System.out.println("========================================================");
		Ticket ticket = ticketService.selectByPrimaryKey("1");
		int tickCount = ticket.getTicketCount();
		synchronized (this) { 
			try {
				if (tickCount > 0) {
					System.out.println( salerName +":"+ tickCount + "已被售出。");
					tickCount = tickCount - 1;
					
					Ticket record = new Ticket();
					record.setId(ticket.getId());
					record.setTicketCount(tickCount);
					int resultInt = ticketService.updateTicketSale(record);
					if(resultInt > 0){
						System.out.println(salerName +":剩下"+ tickCount + "张票。");
					}
				}else{
					System.out.println(salerName +":票已被售完。");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void sale2(String salerName) {
		System.out.println("========================================================");
		Ticket ticket = ticketService.selectByPrimaryKey("1");
		int tickCount = ticket.getTicketCount();
		synchronized (this) { 
			try {
				if (tickCount > 0) {
					System.out.println( salerName +":"+ tickCount + "已被售出。");
					tickCount = tickCount - 1;
					
					Ticket record = new Ticket();
					record.setId(ticket.getId());
					record.setTicketCount(tickCount);
					int resultInt = ticketService.updateTicketSale(record);
					if(resultInt > 0){
						System.out.println(salerName +":剩下"+ tickCount + "张票。");
					}
				}else{
					System.out.println(salerName +":票已被售完。");
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public void sale(String salerName) {
		System.out.println("========================================================");
		Ticket ticket = ticketService.selectByPrimaryKey("1");
		int tickCount = ticket.getTicketCount();
		
		//Lock lock = new ReentrantLock();
		lock.lock();
		try {
			if (tickCount > 0) {
				System.out.println( salerName +":"+ tickCount + "已被售出。");
				tickCount = tickCount - 1;
				
				Ticket record = new Ticket();
				record.setId(ticket.getId());
				record.setTicketCount(tickCount);
				int resultInt = ticketService.updateTicketSale(record);
				if(resultInt > 0){
					System.out.println(salerName +":剩下"+ tickCount + "张票。");
				}
			}else{
				System.out.println(salerName +":已被售完。");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	

}
